<?php
/**
 * @author spenceryg
 * @date 2023/5/22
 * @time 4:11 下午
 * @focus love & life
 */


namespace app\api\controller;


use app\admin\controller\sys\business\SpConfigBusiness;
use think\worker\Server;

class Worker extends Server
{


    protected $socket = 'websocket://0.0.0.0:2346';

    public function onConnect($connection)
    {
        echo "Connected，ID：" . $connection->id . "\n";
        echo "Connected，ID222：" . $connection->id . "\n";
        $connection->send(json_encode(['type' => 'init']));
    }

    public function onMessage($connection, $data)
    {
        SpConfigBusiness::setConfig();
        echo '新的消息' . json_encode($data) . "\n";
        $data = json_decode($data, true);
        if($data['type'] == 'chat'){
            Common::generateCopywritingSocket($connection,$data['key']);
            $connection->send(json_encode(['type' => 'close']));
        }

        if($data['type'] == 'chatDog'){
            Common::generateChatMsgSocket($connection,$data['key'],$data['chat_id']);
            $connection->send(json_encode(['type' => 'close']));
        }

        if($data['type'] == 'title'){
            Common::generateTitleSocket($connection,$data['key'],$data['generated_quantity'] + 1);
            $connection->send(json_encode(['type' => 'close']));
        }


    }

    public function onClose($connection)
    {
        echo "closed，ID：" . $connection->id . "\n";
    }

    public function onError($connection, $code, $msg)
    {
        echo 'onError' . "\n";
        $connection->close();
    }
}
